
	mui.init({});		
	var userinfo = app.getState() || {};
    var uid = userinfo.user_id;

	mui.plusReady(function() {
		var goods_id=plus.webview.currentWebview().goods_id;
		mui.ajax({
				url: apiurl + "Store/edit_shop/",
				data: {'goods_id':goods_id,'_token':userinfo.token},
				async: true,
				dataType: 'json',
				crossDomain: true, //强制使用5+跨域
				type: 'get',
				timeout: 10000,
				success: function(res) {
					console.log(JSON.stringify(res));
					if(res.status ==-3){
						mui.toast(res.msg);
						app.out();
						return false;
					}
					
					if(res.status ==0) {
						mui.alert(res.msg);
						return false;
					}
					document.getElementById('textarea').value=res.good.goods_name;
					document.getElementById('shop_price').value=res.good.shop_price;
					document.getElementById('store_count').value=res.good.store_count;
					document.getElementById('goods_remark').value=res.good.goods_remark;
					document.getElementById('service_tel').value=res.good.service_tel;
					document.getElementById('shipping_price').value=res.good.shipping_price;
					if(res.good.original_img && res.good.original_img.indexOf('Uploads') !== -1){
				    	//document.getElementById('original_img').src=serverurl + res.good.original_img;
				        if(res.good.original_img.indexOf(upurl+'Uploads') !== -1){
							document.getElementById('original_img').src=res.good.original_img;
						}
						else{
							document.getElementById('original_img').src=upurl+res.good.original_img;
						}
				        document.getElementById('original_img').setAttribute('old-original_img',1);
				        document.getElementById('upload_original_img').innerHTML="已选择图片";
					}
				    else{
				    	document.getElementById('original_img').src='';
				    	document.getElementById('original_img').setAttribute('old-original_img',0);
				    	document.getElementById('upload_original_img').innerHTML="请上传1080px*1080px小于1M的JPG图片";
				    }
					var obj=res.goods_images;
					var htm='';
					for(z in obj){
						htm+='<li>';
						htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
						if(obj[z]['image_url'].indexOf(upurl+'Uploads') !== -1){
							var img_url=obj[z]['image_url'];
						}
						else{
							var img_url=upurl+obj[z]['image_url'];
						}
					
						htm+='<img src="'+img_url +'" width="34px" height="34px" old-imgs="'+img_url+'" />';
						htm+='</li>';
					}
					$('.add-img .des-img #goods_images').append(htm);
					
					obj=res.goods_detail_images;
					htm='';
					for(z in obj){
						htm+='<li>';
						htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
						if(obj[z]['image_url'].indexOf(upurl+'Uploads') !== -1){
							var img_url=obj[z]['image_url'];
						}
						else{
							var img_url=upurl+obj[z]['image_url'];
						}
						htm+='<img src="'+img_url+'" width="40px" height="40px" old-imgs="'+img_url+'"/>';
						htm+='</li>';
					}
					$('.goods-des .des-img #goods_detail_img').append(htm);
				},
				error: function(xhr, type, errorThrown) {
					//console.log(JSON.stringify(xhr));
					//console.log(JSON.stringify(type));
					//console.log(JSON.stringify(errorThrown));
					mui.toast('操作失败！');
				}
			});
			
			
        document.getElementById('do_edit').addEventListener('tap', function() {
			  var Info={
			  	user_id: uid,
			  	goods_id: goods_id,
			  	goods_name: document.getElementById('textarea').value.trim(),
			  	shop_price: document.getElementById('shop_price').value.trim(),
			  	store_count: document.getElementById('store_count').value.trim(),
			  	shipping_price: document.getElementById('shipping_price').value.trim(),
			  	goods_remark: document.getElementById('goods_remark').value.trim(),
			  	service_tel: document.getElementById('service_tel').value.trim(),
			  	_token:userinfo.token
			  };
			  document.getElementById('do_edit').disabled="disabled";
			  plus.nativeUI.showWaiting(); 
			  
			  if(Info.goods_name==''){
			  	mui.alert('商品名称不能为空');
			  	plus.nativeUI.closeWaiting();  
			  	document.getElementById('do_edit').disabled="";
			  	return false;
			  }
			  if(Info.goods_name.length>30){
			  	mui.alert('商品名称不能大于30个字');
			  	plus.nativeUI.closeWaiting();  
			  	document.getElementById('do_edit').disabled="";
			  	return false;
			  }
			  if(Info.shop_price=='' || Info.shop_price<=0){
			  	mui.alert('商品价格要大于0');
			  	plus.nativeUI.closeWaiting();  
			  	document.getElementById('do_edit').disabled="";
			  	return false;
			  }
			  
			  if(Info.store_count==''){
			  	mui.alert('商品库存不能为空');
			  	plus.nativeUI.closeWaiting();
			  	document.getElementById('do_edit').disabled="";
			  	return false;
			  }
			  if(Info.goods_remark==''){
			  	mui.alert('商品描述不能为空');
			  	plus.nativeUI.closeWaiting();
			  	document.getElementById('do_edit').disabled="";
			  	return false;
			  }
			  if(Info.service_tel==''){
			  	mui.alert('客服电话不能为空');
			  	plus.nativeUI.closeWaiting();
			  	document.getElementById('do_edit').disabled="";
			  	return false;
			  }
			  if(document.getElementById('upload_original_img').innerHTML!='已选择图片'){
			  	mui.alert('商品图片不能为空');
			  	plus.nativeUI.closeWaiting();
			  	document.getElementById('do_edit').disabled="";
			  	return false;
			  }
			  
			
            if(document.getElementById('original_img').src!='' && document.getElementById('original_img').getAttribute('old-original_img')=='0'){
            	//var base_img=uploadImg(document.getElementById('original_img').src);
            	Info.original_img=document.getElementById('original_img').src;
            }

            if($('.add-img .des-img #goods_images li').length>0){
            	var img_arr=new Array();
            	$('.add-img .des-img #goods_images li').each(function(index){
            		//var base_img=uploadImg($(this).find('img').attr('src'));
            		img_arr.push($(this).find('img').attr('src'));
            	});
            	/*var base_img2=uploadImg(document.getElementById('original_img').src);
            	img_arr.push(base_img2);*/
            	
            	Info.goods_images=img_arr;
            }
        
            if($('.goods-des .des-img #goods_detail_img li').length>0){
            	var img_arr2=new Array();
            	$('.goods-des .des-img #goods_detail_img li').each(function(index){
            			//var base_img=uploadImg($(this).find('img').attr('src'));
            			img_arr2.push($(this).find('img').attr('src'));
            	});
            	Info.goods_detail_images=img_arr2;
           }
           //console.log(JSON.stringify(Info.original_img));
           
           mui.ajax({
				url: apiurl + "Store/edit_shop/",
				data: Info,
				async: true,
				dataType: 'json',
				crossDomain: true, //强制使用5+跨域
				type: 'post',
				timeout: 10000,
				success: function(res) {
					plus.nativeUI.closeWaiting();  
					console.log(JSON.stringify(res));
					if(res.status ==-3){
						mui.toast(res.msg);
						app.out();
						return false;
					}
					
					if(res.status==0){
						mui.alert(res.msg);
					}
					else{
						document.getElementById('do_edit').disabled="";
						mui.toast(res.msg);
						mui.fire(plus.webview.getWebviewById('shop-manage.html'), 'refresh_data');
						mui.back();
						//location.href=location;
					}
					
				},
				error: function(xhr, type, errorThrown) {
					//console.log(JSON.stringify(xhr));
					//console.log(JSON.stringify(type));
					//console.log(JSON.stringify(errorThrown));
					mui.toast('操作失败！');
				}
			});
		}, false);


		mui('body').on('tap', '.mui-popover-action.original_img li>a', function() {
			var a = this,
				parent;
			//根据点击按钮，反推当前是哪个actionsheet
			for (parent = a.parentNode; parent != document.body; parent = parent.parentNode) {
				if (parent.classList.contains('mui-popover-action')) {
					break;
				}
			}
			//关闭actionsheet
			mui('#' + parent.id).popover('toggle');
			if(a.getAttribute('data-id')=='xiangce'){
				//从相册选择
				galleryImg('original_img');
				return false;
			}
			if(a.getAttribute('data-id')=='paizao'){
				//拍照
				getImage('original_img');
				return false;
			}
		})
		
		mui('body').on('tap', '.mui-popover-action.goods_images li>a', function() {
			var a = this,
				parent;
			//根据点击按钮，反推当前是哪个actionsheet
			for (parent = a.parentNode; parent != document.body; parent = parent.parentNode) {
				if (parent.classList.contains('mui-popover-action')) {
					break;
				}
			}
			//关闭actionsheet
			mui('#' + parent.id).popover('toggle');
			if(a.getAttribute('data-id')=='xiangce'){
				//从相册选择
				galleryImg('goods_images');
				return false;
			}
			if(a.getAttribute('data-id')=='paizao'){
				//拍照
				getImage('goods_images');
				return false;
			}
		})
		
		mui('body').on('tap', '.mui-popover-action.goods_detail li>a', function() {
			var a = this,
				parent;
			//根据点击按钮，反推当前是哪个actionsheet
			for (parent = a.parentNode; parent != document.body; parent = parent.parentNode) {
				if (parent.classList.contains('mui-popover-action')) {
					break;
				}
			}
			//关闭actionsheet
			mui('#' + parent.id).popover('toggle');
			if(a.getAttribute('data-id')=='xiangce'){
				//从相册选择
				galleryImg('goods_detail');
				return false;
			}
			if(a.getAttribute('data-id')=='paizao'){
				//拍照
				getImage('goods_detail');
				return false;
			}
		})
		
		//拍照
		function getImage(type) {
			var c = plus.camera.getCamera();
			c.captureImage(function(e) {
				plus.io.resolveLocalFileSystemURL(e, function(entry) {
					var s = entry.toLocalURL() + "?version=" + new Date().getTime();
					console.log(s);
					uploadImg(s,type);
					/*
					if(type=='original_img'){
						document.getElementById('upload_original_img').innerHTML='已选择图片';
						document.getElementById('original_img').src=s;
						document.getElementById('original_img').setAttribute('old-original_img',0);
					}
					else if(type=='goods_images'){
						//document.getElementById("headimg").src = s;
						//uploadImg(s);						
						if($('.add-img .des-img #goods_images li').length==5){
						    mui.alert('最多可添加5张图片');
						    return false;
						}
						var htm='';
						htm+='<li>';
						htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
						htm+='<img src="'+s+'" width="34px" height="34px" old-imgs="" />';
						htm+='</li>';
						$('.add-img .des-img #goods_images').append(htm);
					}
					else if(type=='goods_detail'){
						if($('.goods-des .des-img #goods_detail_img li').length==3){
						    mui.alert('最多可添加3张图片');
						    return false;
						}
						var htm='';
						htm+='<li>';
						htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
						htm+='<img src="'+s+'" width="40px" height="40px" old-imgs="" />';
						htm+='</li>';
						$('.goods-des .des-img #goods_detail_img').append(htm);
					}*/
					//变更大图预览的src
					//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
					document.querySelector("#__mui-imageview__group .mui-slider-item img").src = s + "?version=" + new Date().getTime();
				}, function(e) {
					console.log("读取拍照文件错误：" + e.message);
				});
			}, function(s) {
				console.log("error" + s);
			}, {
				filename: "_doc/head.jpg"
			})
		}
		
		
		//相册
		function galleryImg(type) {
			plus.gallery.pick(function(a) {
				plus.io.resolveLocalFileSystemURL(a, function(entry) {
					plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
						root.getFile("head.jpg", {}, function(file) {
							//文件已存在
							file.remove(function() {
								console.log("file remove success");
								entry.copyTo(root, 'head.jpg', function(e) {
										var e = e.fullPath + "?version=" + new Date().getTime();
										uploadImg(e,type);
										/*if(type=='original_img'){
											document.getElementById('upload_original_img').innerHTML='已选择图片';
										    document.getElementById('original_img').src=e;
										    document.getElementById('original_img').setAttribute('old-original_img',0);
										}
										else if(type=='goods_images'){
											//document.getElementById("headimg").src = s;
											//uploadImg(s);
											if($('.add-img .des-img #goods_images li').length==5){
											    mui.alert('最多可添加5张图片');
											    return false;
											}
											var htm='';
											htm+='<li>';
											htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
											htm+='<img src="'+e+'" width="34px" height="34px" old-imgs="" />';
											htm+='</li>';
											$('.add-img .des-img #goods_images').append(htm);
											
										}
										else if(type=='goods_detail'){
											if($('.goods-des .des-img #goods_detail_img li').length==3){
											    mui.alert('最多可添加3张图片');
											    return false;
											}
											var htm='';
											htm+='<li>';
											htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
											htm+='<img src="'+e+'" width="40px" height="40px" old-imgs="" />';
											htm+='</li>';
											$('.goods-des .des-img #goods_detail_img').append(htm);
										}
										*/
										//变更大图预览的src
										//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
										document.querySelector("#__mui-imageview__group .mui-slider-item img").src = e + "?version=" + new Date().getTime();;
									},
									function(e) {
										console.log('copy image fail:' + e.message);
									});
							}, function() {
								console.log("delete image fail:" + e.message);
							});
						}, function() {
							//文件不存在
							entry.copyTo(root, 'head.jpg', function(e) {
									var path = e.fullPath + "?version=" + new Date().getTime();
									document.getElementById("headimg").src = path;
									//document.getElementById("head-img1").src = path;
									//变更大图预览的src
									//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
									document.querySelector("#__mui-imageview__group .mui-slider-item img").src = path;
								},
								function(e) {
									console.log('copy image fail:' + e.message);
								});
						});
					}, function(e) {
						console.log("get _www folder fail");
					})
				}, function(e) {
					console.log("读取拍照文件错误：" + e.message);
				});
			}, function(a) {}, {
				filter: "image"
			})
		}


         //压缩图片   成64位编码
         function uploadImg11(path) {
			var img = new Image();
			img.src = path;
			//生成比例 
			var w = img.width,
				h = img.height,
				scale = w / h;
			
			//console.log(img.width);
		    //console.log(img.height);
			w = 480 || w; //480  你想压缩到多大
			h = w / scale;
		    //生成canvas
			var canvas = document.createElement('canvas');
			var ctx = canvas.getContext('2d');
			canvas.setAttribute('width', w);
			canvas.setAttribute('height', h);
			ctx.drawImage(img, 0, 0, w, h);
			var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8); //1z 表示图片质量，越低越模糊。	 
			//console.log(base64);
			base64 = base64.replace('data:image/jpeg;base64,', '');
			return base64;
		}
         
        function uploadImg(path,type) {
			var direct='goods/'+type;
			if(type=='goods_detail'){
				direct='goods/goods_detail_images';
			}
			var img = new Image();
			img.src = path;
			img.onload = function() {
				var that = this;
				//生成比例 
				var w = that.width,
					h = that.height,
					scale = w / h;
				w = 480 || w; //480  你想压缩到多大
				h = w / scale;
		
				//生成canvas
				var canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');
				canvas.setAttribute('width', w);
				canvas.setAttribute('height', h);
				ctx.drawImage(that, 0, 0, w, h);
				var base64 = canvas.toDataURL('image/jpeg', 1 || 0.8); //1z 表示图片质量，越低越模糊。	 
				console.log(base64);
				//base64 = base64.replace('data:image/jpeg;base64,', '');
				mui.post(uploadurl, {
					file: base64,
					uid: uid,
					path : path,
					name : direct
				}, function(res) {
					console.log(JSON.stringify(res));
					if(res.status > 0) {
						//var img_path=serverurl + 'Uploads/trade/' + trade_id + '.jpg';
						var img_path = res.url;
						mui.toast('上传成功！');
						if(type=='original_img'){
							document.getElementById('upload_original_img').innerHTML='已选择图片';
							document.getElementById('original_img').src=img_path;
							document.getElementById('original_img').setAttribute('old-original_img',0);
						}
						else if(type=='goods_images'){					
							if($('.add-img .des-img #goods_images li').length==5){
							    mui.alert('最多可添加5张图片');
							    return false;
							}
							var htm='';
							htm+='<li>';
							htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
							htm+='<img src="'+img_path+'" width="34px" height="34px" old-imgs="" />';
							htm+='</li>';
							$('.add-img .des-img #goods_images').append(htm);
						}
						else if(type=='goods_detail'){
							if($('.goods-des .des-img #goods_detail_img li').length==3){
							    mui.alert('最多可添加3张图片');
							    return false;
							}
							var htm='';
							htm+='<li>';
							htm+='<span class="mui-icon mui-icon-close" onclick="del_img(this)"></span>';
							htm+='<img src="'+img_path+'" width="40px" height="40px" old-imgs="" />';
							htm+='</li>';
							$('.goods-des .des-img #goods_detail_img').append(htm);
						}
						
					}
				},'json');
		
			}
		}

	});
	
	  //删除图片
		function del_img(obj){
			var liob=$(obj).parent('li');
			liob.remove();
		}
